﻿using System;
using XamlingCore.Infrastructure.LocalStorage;
using XamlingCore.Infrastructure.Resource;
using XamlingCore.Infrastructure.Serialisation;
using XamlingCore.Infrastructure.SystemMessage;

namespace XamlingCore.Infrastructure.Repository
{
    public class RepositoryBase
    {
        protected bool HandleError(Exception ex, string messageTitle)
        {
            if(ex!=null)
            {
                var message = new SystemMessagePackage()
                {
                    Data = ex,
                    IsError = true,
                    Message = ex.ToString(),
                    Title = messageTitle
                };
                SendMessage(message);
                return true;
            }

            return false;
        }
        
        protected void SendMessage(SystemMessagePackage message)
        {
            if(message!=null && MessageCallback!=null)
            {
                MessageCallback(message);
            }
        }

        protected string SerialiseEntity<T>(T entity)
        {
            return Serialise.SerialiseEntity(entity);
        }

        protected T DeserialiseEntity<T>(string data)
        {
            return Serialise.DeSerialiseEntity<T>(data);
        }

        protected void SerialiseAndSaveEntity<T>(T entity, string fileName)
        {
            var data = Serialise.SerialiseEntity(entity);
            LocalStorageHelper.Save(data, fileName);
        }

        public Action<SystemMessagePackage> MessageCallback { get; set; }
    }
}
